/*
 * PainelContatos.java
 *
 * Created on 14 de Outubro de 2009, 13:33
 */

package agendaBD;

import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.JTextComponent;

/**
 *
 * @author  07205156
 */
public class PainelContatos extends javax.swing.JPanel {
    
    public static final int EDITING = 0;
    
    public static final int VIEWING = 1;

    public static final int CREATING = 2;
    
    private int status = VIEWING;
    
    private CustomTreeCellRenderer treeCellRenderer = new CustomTreeCellRenderer();

    private ContatosTreeModel treeModel = new ContatosTreeModel();

    private Contato currentContato;

    /** Creates new form PainelContatos */
    public PainelContatos() {
        initComponents();
        
        this.setEditable(false);
        this.status = VIEWING;

        this.treeCellRenderer.addIcon("contato", new ImageIcon(PainelContatos.class.getResource("/agendaBD/imagens/Star.png")));
        this.treeCellRenderer.addIcon("Amigos", new ImageIcon(PainelContatos.class.getResource("/agendaBD/imagens/amigos_hab.jpg")));
        this.treeCellRenderer.addIcon("Família", new ImageIcon(PainelContatos.class.getResource("/agendaBD/imagens/familia_hab.jpg")));
        this.treeCellRenderer.addIcon("Profissional", new ImageIcon(PainelContatos.class.getResource("/agendaBD/imagens/profissional_hab.jpg")));
        this.treeCellRenderer.addIcon("Professor", new ImageIcon(PainelContatos.class.getResource("/agendaBD/imagens/Luma-green.png")));

        this.treeContatos.updateUI();

        this.btnEditar.setEnabled(false);

        this.btnExcluir.setEnabled(false);

         //Obtenho a lista de categorias.
        final List<String> categoria = new ArrayList<String>();

        Object treeRoot = this.treeModel.getRoot();

        for(int i = 0; i < this.treeModel.getChildCount(treeRoot); i++){
            categoria.add(this.treeModel.getChild(treeRoot, i).toString());
        }

        this.cmbTipo.removeAllItems();

        for(String strCategoria : categoria){
            this.cmbTipo.addItem(strCategoria);
        }

        this.sldFaccon.getModel().addChangeListener(new ChangeListener() {

            public void stateChanged(ChangeEvent e) {
                PainelContatos.this.lblFaccon.setText(
                        PainelContatos.this.sldFaccon.getValue()+""
                        );

               PainelContatos.this.icoFaccon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/agendaBD/imagens/"+PainelContatos.this.lblFaccon.getText()+".png")));
            }
        });

        pnlTeacherOptions.setVisible(false);
    }
    
    public void setEditable(boolean e){
       
        this.setTextFieldEditable(this.txtNome, e);
        this.setTextFieldEditable(this.txtSobrenome, e);    
        this.setTextFieldEditable(this.txtApelido, e);
        this.setTextFieldEditable(this.txtFtp, e);
        this.setTextFieldEditable(this.txaEndereco, e);
        
        this.cmbTipo.setEditable(e);
        this.sldFaccon.setEnabled(e);

    }

    private void setTextFieldEditable(JTextComponent txt, boolean b){
        
        txt.setEditable(b);
        //txt.setBorder(null);
        //txt.setBorder(b ? UIManager.getBorder("TextField.border") : null);
        
    }

    public void addNotify(){
        super.addNotify();
        this.loadContatos();
    }

    public void loadContatos(){

        //Obtenho a lista de categorias.
        final List<String> categoria = new ArrayList<String>();

        Object treeRoot = this.treeModel.getRoot();

        for(int i = 0; i < this.treeModel.getChildCount(treeRoot); i++){
            categoria.add(this.treeModel.getChild(treeRoot, i).toString());
        }

        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        SwingWorker<Integer,Object> bdworker = new SwingWorker<Integer, Object>(){

            @Override
            protected Integer doInBackground() throws Exception {
                 try {

                     for(String cName : categoria){
                        this.loadContatos(cName);
                     }

                } catch (Exception ex) {
                    this.publish(ex);
                }

                return 0;
            }

            protected void loadContatos(String categoria)throws Exception{
                String sqlContato =
                              "SELECT nome, sobrenome FROM CONTATOS WHERE TIPO = '"+categoria.toUpperCase()+"'";

                ResultSet rs = Conexao.getInstance().consultar(sqlContato);

                String nome, sobrenome;

                while(rs.next()){
                    nome = rs.getString("NOME");
                    sobrenome = rs.getString("SOBRENOME");

                    this.publish(new Contato(nome,sobrenome), categoria);
                }
            }

            @Override
            protected void done() {
                PainelContatos.this.setCursor(Cursor.getDefaultCursor());
                PainelContatos.this.treeContatos.updateUI();
            }
            
            @Override
            protected void process(List<Object> chunks) {

                if(chunks.get(0) instanceof Throwable){

                    Throwable t = (Throwable) chunks.get(0);
                    JOptionPane.showMessageDialog(
                            PainelContatos.this,
                            t.getMessage(),
                            "Erro na comunicação com o banco de dados.",
                            JOptionPane.ERROR_MESSAGE);
                }
                else if(chunks.get(0) instanceof Contato){

                    for(int i = 0; i < chunks.size(); i+=2){
                        Contato contato = (Contato) chunks.get(i);

                        String categoria = (String) chunks.get(i+1);

                        PainelContatos.this.treeModel.addContato(contato, categoria);
                    }
                }
            }
        };

        bdworker.execute();
    }

    public void loadContato(final Contato c){

        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            
        SwingWorker<Integer,Object> loadWorder = new SwingWorker<Integer, Object>() {

            @Override
            protected Integer doInBackground() throws Exception {

                String query = "SELECT * FROM CONTATOS WHERE NOME='"+
                        c.getNome() + "' AND SOBRENOME='"+c.getSobrenome()+"'";

                try{
                    ResultSet rs = Conexao.getInstance().consultar(query);
               
                    if(rs.next()){

                        c.setNome(rs.getString("NOME"));
                        c.setSobrenome(rs.getString("SOBRENOME"));
                        c.setApelido(rs.getString("APELIDO"));
                        c.setEndereco(rs.getString("ENDEREÇO"));
                        c.setTipo(rs.getString("TIPO"));

                    }

                    if(c.getTipo().toUpperCase().equals("PROFESSOR")){

                        String queryProf =
                                "SELECT * FROM PROFESSORES WHERE NOME ='"+
                                c.getNome()+"' AND SOBRENOME='"+c.getSobrenome()+"'";

                        ResultSet rsP = Conexao.getInstance().consultar(queryProf);
                        
                        if(rsP.next()){
                            
                            c.setFtp(rsP.getString("PÁGINA_DA_INTERNET"));
                            c.setFaccon(rsP.getString("FACILIDADE_DE_CONVÍVIO"));
                          
                            
                        }

                    }

                }catch(Exception e){
                    this.publish(e);
                }

                return 0;
            }

            @Override
            protected void done() {
               PainelContatos.this.setCursor(Cursor.getDefaultCursor());
               PainelContatos.this.showContato(c);
            }

            @Override
            protected void process(List<Object> chunks) {
                if(chunks.get(0) instanceof Throwable){

                    Throwable t = (Throwable) chunks.get(0);

                    JOptionPane.showMessageDialog(
                            PainelContatos.this, t.getMessage(),
                            "Erro de comunicação com o Banco de dado.",
                            JOptionPane.ERROR_MESSAGE);
                }
            }

        };

        loadWorder.execute();
    }

    public void showContato(Contato c){

        this.txtNome.setText(c.getNome());
        this.txtSobrenome.setText(c.getSobrenome());
        this.txtApelido.setText(c.getApelido());
        this.txaEndereco.setText(c.getEndereco());

        for(int i = 0; i < this.cmbTipo.getItemCount(); i++){

            if(this.cmbTipo.getItemAt(i).toString().toUpperCase().equals(c.getTipo().toUpperCase())){
                this.cmbTipo.setSelectedIndex(i);
            }

        }

        if(c.getTipo().toUpperCase().equals("PROFESSOR")){
            this.txtFtp.setText(c.getFtp());

            try{
                this.sldFaccon.setValue(Integer.parseInt(c.getFaccon()));
            }
            catch(NumberFormatException nfe){
                this.sldFaccon.setValue(5);
            }
        }
        else{
            this.txtFtp.setText("");
            this.sldFaccon.setValue(5);
        }

        this.btnEditar.setEnabled(true);
        this.btnExcluir.setEnabled(true);

        this.btnEditar.setText("Editar");
        this.btnExcluir.setText("Excluir");

        this.setEditable(false);

        this.status = VIEWING;

        this.currentContato = c;



    }

    public void clear(){

        this.txtNome.setText("");
        this.txtSobrenome.setText("");
        this.txtApelido.setText("");
        this.txaEndereco.setText("");
        this.cmbTipo.setSelectedIndex(0);

        this.btnEditar.setEnabled(false);
        this.btnExcluir.setEnabled(false);
        
    }

    public void editContato(Contato c){

        this.currentContato = c;
        this.status = EDITING;

    }

    public void novoContato(Contato c){

        this.clear();

        this.currentContato = c;

        this.status = CREATING;

        this.btnEditar.setText("Novo");
        this.btnExcluir.setText("Cancelar");
        this.btnEditar.setEnabled(true);
        this.btnExcluir.setEnabled(true);


        this.setEditable(true);


        
    }

    public void updateContato(final Contato c, final String nome, final String sobrenome){

        final Contato nc = new Contato("", "");

        nc.setNome(this.txtNome.getText());
        nc.setSobrenome(this.txtSobrenome.getText());
        nc.setApelido(this.txtApelido.getText());
        nc.setEndereco(this.txaEndereco.getText());
        nc.setTipo(this.cmbTipo.getSelectedItem().toString());

        //USo caso seja um professor (PUTA GAMBIARRA!!! HEHEHE)
        final String ftp = this.txtFtp.getText();
        final String facilidadeConvivio = this.sldFaccon.getValue()+"";

        nc.setFaccon(facilidadeConvivio);
        nc.setFtp(ftp);

        SwingWorker<Integer, Object> deleteWorker = new SwingWorker<Integer, Object>() {

            @Override
            protected Integer doInBackground() throws Exception {

                try{

                    String set = "NOME = '" + nc.getNome() + "'";
                    set += ",SOBRENOME = '" + nc.getSobrenome() + "'";
                    set += ",APELIDO = '" + nc.getApelido() + "'";
                    set += ",ENDEREÇO = '" + nc.getEndereco() + "'";
                    set += ",TIPO = '" + nc.getTipo().toUpperCase() + "'";

                    String sql = "UPDATE CONTATOS SET " + set + " WHERE NOME='" +
                            nome +"' AND SOBRENOME='"+sobrenome+"'";

                    Conexao.getInstance().executar(sql);

                    if(nc.getTipo().toUpperCase().equals("PROFESSOR")){
                         //Se agora sou um professor, atualizo a tabela de professores
                         //Se eu deixei de ser, triggers cuidam disto
                         //Criar registro em professor também é papel das trigger.

                        String setProf = "PÁGINA_DA_INTERNET = '" + ftp + "'";
                            setProf += ",FACILIDADE_DE_CONVÍVIO = '"+facilidadeConvivio+"'";

                        String sqlProf = "UPDATE PROFESSORES SET " + setProf +
                                " WHERE nome = '"+nc.getNome()+
                                "' AND sobrenome = '"
                                + nc.getSobrenome() + "'";

                        Conexao.getInstance().executar(sqlProf);
                    }

                    publish(nc);


                }
                catch(Exception e){
                    publish(e);
                    return -1;
                }

                return 0;
            }

            @Override
            protected void done() {
                try {
                    if (this.get() == 0) {
                        JOptionPane.showMessageDialog(PainelContatos.this, "Contato atualizado com sucesso.");

                        PainelContatos.this.treeModel.addContato(nc, nc.getTipo());

                        PainelContatos.this.showContato(nc);
                        
                        PainelContatos.this.treeContatos.updateUI();


                    }
                    else{
                        PainelContatos.this.setEditable(true);
                        PainelContatos.this.editContato(nc);
                    }
                } catch (InterruptedException ex) {
                    Logger.getLogger(PainelContatos.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(PainelContatos.class.getName()).log(Level.SEVERE, null, ex);
                }

                PainelContatos.this.setCursor(Cursor.getDefaultCursor());
            }

            public void process(List<Object> obj){

                if(obj.get(0) instanceof Throwable){

                    Throwable t = (Throwable) obj.get(0);

                    JOptionPane.showMessageDialog(PainelContatos.this, t.getMessage(),
                            "Erro ao atualizar contato do banco de dados.", JOptionPane.ERROR_MESSAGE);
                }
                else if(obj.get(0) instanceof Contato){
                }

            }
        };

        deleteWorker.execute();

    }

    public void excluirContato(final Contato c){

        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        SwingWorker<Integer, Object> deleteWorker = new SwingWorker<Integer, Object>() {

            @Override
            protected Integer doInBackground() throws Exception {

                try{

                    String sql = "DELETE FROM CONTATOS WHERE NOME='" +
                            c.getNome()+"' AND SOBRENOME='"+c.getSobrenome()+"'";

                    Conexao.getInstance().executar(sql);

                    publish(c);


                }
                catch(Exception e){
                    publish(e);
                    return -1;
                }

                return 0;
            }

            @Override
            protected void done() {
                try {
                    if (this.get() == 0) {
                        JOptionPane.showMessageDialog(PainelContatos.this, "Contato removido com sucesso.");

                        PainelContatos.this.clear();
                        PainelContatos.this.currentContato = null;
                    }
                } catch (InterruptedException ex) {
                    Logger.getLogger(PainelContatos.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(PainelContatos.class.getName()).log(Level.SEVERE, null, ex);
                }

                PainelContatos.this.setCursor(Cursor.getDefaultCursor());
            }

            public void process(List<Object> obj){
                
                if(obj.get(0) instanceof Throwable){

                    Throwable t = (Throwable) obj.get(0);

                    JOptionPane.showMessageDialog(PainelContatos.this, t.getMessage(),
                            "Erro ao apagar contato do banco de dados.", JOptionPane.ERROR_MESSAGE);
                }
                else if(obj.get(0) instanceof Contato){

                    PainelContatos.this.treeModel.delContato((Contato)obj.get(0));

                    PainelContatos.this.treeContatos.updateUI();

                }

            }
        };

        deleteWorker.execute();
    }

    public void createContato(final Contato c){
       
        c.setApelido(this.txtApelido.getText());
        c.setEndereco(this.txaEndereco.getText());
        c.setTipo(this.cmbTipo.getSelectedItem().toString());


        if(c.getTipo().toUpperCase().equals("PROFESSOR")){
            c.setFtp(this.txtFtp.getText());
            c.setFaccon(this.sldFaccon.getValue()+"");
        }

        SwingWorker<Integer, Object> creatWorker = new SwingWorker<Integer, Object>() {

            @Override
            protected Integer doInBackground() throws Exception {

                try{

                    String values = "('"+c.getNome()+"'";
                    values += ",'" + c.getSobrenome() + "'";
                    values += ",'" + c.getApelido() + "'";
                    values += ",'" + c.getEndereco() + "'";
                    values += ",'" + c.getTipo().toUpperCase() + "')";

                    String sql = "INSERT INTO CONTATOS (NOME, SOBRENOME, APELIDO, ENDEREÇO, TIPO)";

                    sql += " VALUES " + values;
                   
                    Conexao.getInstance().executar(sql);

                    if(c.getTipo().toUpperCase().equals("PROFESSOR")){
                         //Se agora sou um professor, atualizo a tabela de professores
                         //Se eu deixei de ser, triggers cuidam disto
                         //Criar registro em professor também é papel das trigger.

                        String setProf = "PÁGINA_DA_INTERNET = '" + c.getFtp() + "'";
                            setProf += ",FACILIDADE_DE_CONVÍVIO = '"+c.getFaccon()+"'";

                        String sqlProf = "UPDATE PROFESSORES SET " + setProf +
                                " WHERE nome = '"+c.getNome()+
                                "' AND sobrenome = '"
                                + c.getSobrenome() + "'";

                        Conexao.getInstance().executar(sqlProf);
                    }


                    publish(c);


                }
                catch(Exception e){
                    publish(e);
                    return -1;
                }

                return 0;
            }

            @Override
            protected void done() {
                try {
                    if (this.get() == 0) {
                        JOptionPane.showMessageDialog(PainelContatos.this, "Contato cadastrado com sucesso.");

                        PainelContatos.this.treeModel.addContato(c, c.getTipo());

                        PainelContatos.this.treeContatos.updateUI();



                    }
                } catch (InterruptedException ex) {
                    Logger.getLogger(PainelContatos.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(PainelContatos.class.getName()).log(Level.SEVERE, null, ex);
                }

                PainelContatos.this.setCursor(Cursor.getDefaultCursor());
            }

            public void process(List<Object> obj){

                if(obj.get(0) instanceof Throwable){

                    Throwable t = (Throwable) obj.get(0);

                    JOptionPane.showMessageDialog(PainelContatos.this, t.getMessage(),
                            "Erro ao atualizar contato do banco de dados.", JOptionPane.ERROR_MESSAGE);
                }
                else if(obj.get(0) instanceof Contato){
                }

            }
        };

        creatWorker.execute();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        ppmContato = new javax.swing.JPopupMenu();
        mtnNovoContato = new javax.swing.JMenuItem();
        pnlController = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        treeContatos = new javax.swing.JTree();
        jButton1 = new javax.swing.JButton();
        pnlContent = new javax.swing.JPanel();
        btnEditar = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        pnlTeacherOptions = new javax.swing.JPanel();
        jLabel10 = new javax.swing.JLabel();
        txtFtp = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        sldFaccon = new javax.swing.JSlider();
        lblFaccon = new javax.swing.JLabel();
        icoFaccon = new javax.swing.JLabel();
        cmbTipo = new javax.swing.JComboBox();
        txtNome = new javax.swing.JTextField();
        txtSobrenome = new javax.swing.JTextField();
        txtApelido = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        txaEndereco = new javax.swing.JTextArea();
        pnlHead = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblIcone = new javax.swing.JLabel();

        ppmContato.setInvoker(treeContatos);

        mtnNovoContato.setText("Novo Contato");
        mtnNovoContato.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mtnNovoContatoActionPerformed(evt);
            }
        });
        ppmContato.add(mtnNovoContato);

        setLayout(new java.awt.BorderLayout());

        pnlController.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 5));
        pnlController.setPreferredSize(new java.awt.Dimension(150, 100));

        treeContatos.setModel(this.treeModel);
        treeContatos.setCellRenderer(this.treeCellRenderer);
        treeContatos.setPreferredSize(new java.awt.Dimension(100, 48));
        treeContatos.setRootVisible(false);
        treeContatos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                treeContatosMouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                treeContatosMouseReleased(evt);
            }
        });
        treeContatos.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                treeContatosValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(treeContatos);

        jButton1.setText("Novo Contato");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlControllerLayout = new javax.swing.GroupLayout(pnlController);
        pnlController.setLayout(pnlControllerLayout);
        pnlControllerLayout.setHorizontalGroup(
            pnlControllerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
        );
        pnlControllerLayout.setVerticalGroup(
            pnlControllerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlControllerLayout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE))
        );

        add(pnlController, java.awt.BorderLayout.WEST);

        btnEditar.setText("Editar");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        jLabel4.setText("Nome");

        jLabel5.setText("Sobrenome");

        jLabel6.setText("Endereço");

        jLabel7.setText("Tipo");

        jLabel8.setText("Apelido");

        jLabel10.setText("FTP");

        jLabel9.setText("Facilidade de Convívio");

        sldFaccon.setMaximum(10);
        sldFaccon.setValue(0);

        lblFaccon.setText("0");

        icoFaccon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/agendaBD/imagens/5.png"))); // NOI18N

        javax.swing.GroupLayout pnlTeacherOptionsLayout = new javax.swing.GroupLayout(pnlTeacherOptions);
        pnlTeacherOptions.setLayout(pnlTeacherOptionsLayout);
        pnlTeacherOptionsLayout.setHorizontalGroup(
            pnlTeacherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlTeacherOptionsLayout.createSequentialGroup()
                .addGroup(pnlTeacherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel10)
                    .addComponent(txtFtp, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
                    .addComponent(jLabel9)
                    .addComponent(sldFaccon, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblFaccon)
                .addGap(42, 42, 42)
                .addComponent(icoFaccon, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(294, Short.MAX_VALUE))
        );
        pnlTeacherOptionsLayout.setVerticalGroup(
            pnlTeacherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlTeacherOptionsLayout.createSequentialGroup()
                .addComponent(jLabel10)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlTeacherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(icoFaccon, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(pnlTeacherOptionsLayout.createSequentialGroup()
                        .addComponent(txtFtp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(20, 20, 20)
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlTeacherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblFaccon)
                            .addComponent(sldFaccon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(25, Short.MAX_VALUE))
        );

        cmbTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbTipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbTipoActionPerformed(evt);
            }
        });

        txaEndereco.setColumns(20);
        txaEndereco.setRows(5);
        jScrollPane2.setViewportView(txaEndereco);

        javax.swing.GroupLayout pnlContentLayout = new javax.swing.GroupLayout(pnlContent);
        pnlContent.setLayout(pnlContentLayout);
        pnlContentLayout.setHorizontalGroup(
            pnlContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlContentLayout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(pnlContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlContentLayout.createSequentialGroup()
                        .addGroup(pnlContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbTipo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 587, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlContentLayout.createSequentialGroup()
                            .addComponent(jLabel6)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 598, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(pnlContentLayout.createSequentialGroup()
                            .addGroup(pnlContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel4)
                                .addComponent(txtNome, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE))
                            .addGap(11, 11, 11)
                            .addGroup(pnlContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel5)
                                .addComponent(txtSobrenome, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(pnlContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel8)
                                .addComponent(txtApelido, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)))
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 643, Short.MAX_VALUE)
                        .addComponent(pnlTeacherOptions, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(33, 33, 33))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlContentLayout.createSequentialGroup()
                .addContainerGap(424, Short.MAX_VALUE)
                .addComponent(btnEditar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnExcluir)
                .addGap(76, 76, 76))
        );
        pnlContentLayout.setVerticalGroup(
            pnlContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlContentLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlContentLayout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtSobrenome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(34, 34, 34)
                        .addComponent(jLabel6))
                    .addGroup(pnlContentLayout.createSequentialGroup()
                        .addGroup(pnlContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtApelido, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addComponent(pnlTeacherOptions, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addGroup(pnlContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnEditar)
                    .addComponent(btnExcluir))
                .addContainerGap())
        );

        add(pnlContent, java.awt.BorderLayout.CENTER);

        pnlHead.setBackground(new java.awt.Color(255, 255, 255));
        pnlHead.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 20, 1, 20));
        pnlHead.setPreferredSize(new java.awt.Dimension(100, 50));
        pnlHead.setLayout(new java.awt.GridBagLayout());

        jLabel1.setText("CONTATOS");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 0.8;
        pnlHead.add(jLabel1, gridBagConstraints);

        jLabel3.setFont(new java.awt.Font("Monospaced", 0, 10));
        jLabel3.setText("Listar, adicionar, editar e excluir contatos.");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.ipadx = 20;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(2, 0, 0, 0);
        pnlHead.add(jLabel3, gridBagConstraints);

        lblIcone.setIcon(new javax.swing.ImageIcon(getClass().getResource("/agendaBD/imagens/mario.png"))); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        pnlHead.add(lblIcone, gridBagConstraints);

        add(pnlHead, java.awt.BorderLayout.NORTH);
    }// </editor-fold>//GEN-END:initComponents

    private void treeContatosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeContatosMouseClicked

           if(evt.getButton() == MouseEvent.BUTTON3){
               this.ppmContato.setLocation(evt.getX(), evt.getY());
               this.ppmContato.setVisible(true);
           }
        
    }//GEN-LAST:event_treeContatosMouseClicked

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed

        if(this.status == VIEWING){
            this.setEditable(true);
            this.status = EDITING;

            this.btnEditar.setEnabled(true);
            this.btnExcluir.setEnabled(true);
            this.btnEditar.setText("OK");
            this.btnExcluir.setText("Cancelar");
        }
        else if(this.status == EDITING){

            if(this.txtNome.getText().equals("") ||
                    this.txtSobrenome.getText().equals(""))
            {
                JOptionPane.showMessageDialog(
                        this, 
                        "Campo nome e sobrenome são obrigatórios",
                        "Campos não preenchidos",
                        JOptionPane.ERROR_MESSAGE);

                return;
            }

            this.treeModel.delContato(currentContato);
            this.updateContato(currentContato,
                    currentContato.getNome(), currentContato.getSobrenome());

            this.setEditable(false);
            this.status = VIEWING;
        }
        else if(this.status == CREATING){

            if(this.txtNome.getText().equals("") ||
                    this.txtSobrenome.getText().equals(""))
            {
                JOptionPane.showMessageDialog(
                        this,
                        "Campo nome e sobrenome são obrigatórios",
                        "Campos não preenchidos",
                        JOptionPane.ERROR_MESSAGE);

                return;
            }

            currentContato.setNome(this.txtNome.getText());
            currentContato.setSobrenome(this.txtSobrenome.getText());

            this.showContato(currentContato);

            this.createContato(currentContato);
        }
    }//GEN-LAST:event_btnEditarActionPerformed

    private void cmbTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTipoActionPerformed

        Object selected = this.cmbTipo.getSelectedItem();

        if(selected != null)
        {
            this.pnlTeacherOptions.setVisible(selected.toString().equals("Professor"));

            if(selected.toString().equals("Professor"))
            {
                this.txtFtp.setText("");
                this.sldFaccon.setValue(5);
            }
        }
    }//GEN-LAST:event_cmbTipoActionPerformed

    private void treeContatosValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_treeContatosValueChanged


        Object o =
           this.treeContatos.getSelectionModel().getSelectionPath().getLastPathComponent();

        if(o instanceof Contato){

            if(this.status == EDITING){
               int opt = JOptionPane.showConfirmDialog(
                        this,
                        "Há um contato em edição, deseja realmente descartar as modificações.");
            
               if(opt == JOptionPane.NO_OPTION){
                   return;
               }

            }

            this.loadContato((Contato)o);
        }


    }//GEN-LAST:event_treeContatosValueChanged

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed

        if(this.status == VIEWING){
            //Exclui o contato em visualização.
            this.excluirContato(currentContato);

        }
        else if(this.status == EDITING){
            //Cancela a edição
            this.showContato(this.currentContato);
            this.setEditable(false);
            this.status = VIEWING;
            this.btnEditar.setText("Editar");
            this.btnExcluir.setText("Excluir");
        }
        else if(this.status == CREATING){
            this.setEditable(false);
            this.status = VIEWING;
            this.setEditable(false);
            this.btnEditar.setEnabled(false);
            this.btnExcluir.setEnabled(false);
        }

    }//GEN-LAST:event_btnExcluirActionPerformed

    private void mtnNovoContatoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mtnNovoContatoActionPerformed

        //Crio um novo contato

    }//GEN-LAST:event_mtnNovoContatoActionPerformed

    private void treeContatosMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeContatosMouseReleased

//        if(evt.isPopupTrigger()){
//            JComponent source = (JComponent) evt.getSource();
//            ppmContato.show( evt.getComponent(), evt.getX(), evt.getY() );
//        }
    }//GEN-LAST:event_treeContatosMouseReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.novoContato(new Contato("",""));
    }//GEN-LAST:event_jButton1ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JComboBox cmbTipo;
    private javax.swing.JLabel icoFaccon;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblFaccon;
    private javax.swing.JLabel lblIcone;
    private javax.swing.JMenuItem mtnNovoContato;
    private javax.swing.JPanel pnlContent;
    private javax.swing.JPanel pnlController;
    private javax.swing.JPanel pnlHead;
    private javax.swing.JPanel pnlTeacherOptions;
    private javax.swing.JPopupMenu ppmContato;
    private javax.swing.JSlider sldFaccon;
    private javax.swing.JTree treeContatos;
    private javax.swing.JTextArea txaEndereco;
    private javax.swing.JTextField txtApelido;
    private javax.swing.JTextField txtFtp;
    private javax.swing.JTextField txtNome;
    private javax.swing.JTextField txtSobrenome;
    // End of variables declaration//GEN-END:variables

}
